#include <glut.h>
#include <stdio.h>
#include "Fluid2D.h"
#include "Density.h"

// frame dimensions (dxd pixels)
int d = 300;
static GLint    ImageWidth=d;
static GLint    ImageHeight=d;
static GLint    PixelLength=ImageWidth*ImageHeight*3;

// solver variables
int n = 200;
float dt = 0.2f;
float grid=(float)10.0f/n;
Fluid2D *fs = new Fluid2D();

// flag to display velocity field
bool vkey = false;

// mouse position
int x, xOld;
int y, yOld;

// cell index
int i, j;

// cell dimensions
int dg, dg_2;

// cell position
int dx, dy;

// fluid velocity
int u, v;

int c;
int button;

static GLubyte* PixelData;

int debug=0;
bool startdebug=false;


void reshape(int w,int h){
	glViewport(0, 0, (GLsizei) w, (GLsizei) h);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45.0f,(GLfloat) w / (GLfloat)h , 0.5f, -1000.0f);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void init()
{
	glClearColor(0,0,0,0);
	gluOrtho2D(0,ImageWidth,0,ImageHeight);
}

void display(void)
{

	fs->pre_density[100][180] = 100;

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glTranslatef(-4.9,-4.9,-12);

	fs->VelocitySolver();
	fs->DensitySolver();

	float x=0.0, y=0.0;
	float d00, d01, d10, d11;

	glBegin ( GL_QUADS );

	for (int i=0;i<n-1;i++)
	{
		y=0.0;
		for (int j=0;j<n-1;j++)
		{
			d00 = fs->density[i][j];
			d01 = fs->density[i][j+1];
			d10 = fs->density[i+1][j];
			d11 = fs->density[i+1][j+1];

			glColor3f ( d00, d00, d00 ); glVertex3f ( x, y, 0 );
			glColor3f ( d10, d10, d10 ); glVertex3f ( x+grid, y, 0 );
			glColor3f ( d11, d11, d11 ); glVertex3f ( x+grid, y+grid, 0 );
			glColor3f ( d01, d01, d01 ); glVertex3f ( x, y+grid, 0 );

			y+=grid;
		}
		x+=grid;
	}

	glEnd();	

	glutSwapBuffers();
	glutPostRedisplay();
}

void processMouse(int button, int state, int a, int b)
{
	startdebug=true;

	xOld=x;
	yOld=y;
	x=a;
	y=b;

	i = (int) ((x / (float) d) * n );
	j = (int) ((y / (float) d) * n );

	

	fs->pre_density[i][j] = 100;
}

void keyboard(unsigned char key, int x, int y)
{
}

void main(int argc, char* argv[])
{
	PixelData=new GLubyte[PixelLength];
	//reset();
	fs->Setup(n,dt);
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
	glutInitWindowPosition(100, 100);
	glutInitWindowSize(ImageWidth, ImageHeight);
	glutCreateWindow("Rasterization");
	init();
	glutDisplayFunc(display);
	glutMouseFunc(processMouse);
	glutKeyboardFunc(keyboard);
	glutReshapeFunc(reshape);
	glutMainLoop();

	

	for (int i=0;i<100;i++)
	{	
		fs->pre_density[13][12] = 100;
		fs->VelocitySolver();
		fs->DensitySolver();
		printf("hello");
		WriteDensity(fs->density,n);

	}
}